
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animation/DouBao/SoundButton/recorder_copy.dart';
import 'package:flutter_animation/DouBao/SoundButton/wave_copy.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../Utils/ColorUtil.dart';


class SoundsMessageButtonCopy extends StatefulWidget {
  const SoundsMessageButtonCopy({
    super.key,
    required this.editAreaRenderBox,
    this.builder,
    this.onChanged,
    this.onSendSounds,
  });

  /// 自定义发送按钮视图
  final Function(
    BuildContext context,
    SoundsMessageStatus status,
  )? builder;

  /// 输入控件的位置
  final RenderBox? editAreaRenderBox;

  /// 状态监听， 回调到外部自定义处理
  final Function(SoundsMessageStatus status)? onChanged;

  /// 发送音频 / 发送音频文字
  final Function(SendContentType type, String content)? onSendSounds;

  @override
  State<SoundsMessageButtonCopy> createState() => _SoundsMessageButtonCopyState();
}

class _SoundsMessageButtonCopyState extends State<SoundsMessageButtonCopy> {
  /// 遮罩图层
  OverlayEntry? _entry;

  /// 录音
  final _soundsRecorder = SoundsRecorderControllerCopy();

  @override
  void initState() {
    super.initState();
    _soundsRecorder.status.addListener(() {
      widget.onChanged?.call(_soundsRecorder.status.value);
    });
  }

  @override
  void dispose() {
    _soundsRecorder.reset();
    super.dispose();
  }

  _removeMask() {
    if (_entry != null) {
      _entry!.remove();
      _entry = null;
      _soundsRecorder.updateStatus(SoundsMessageStatus.none);
    }
  }

  _showRecordingMask() {
    _entry = OverlayEntry(
      builder: (context) {
        Offset topLeft = widget.editAreaRenderBox!.localToGlobal(Offset.zero);
        Offset bottomRight = topLeft.translate(widget.editAreaRenderBox!.size.width, widget.editAreaRenderBox!.size.height);
        /// 仿豆包语音
        return ValueListenableBuilder(
          valueListenable: _soundsRecorder.status,
          builder: (context, status, child) {
            return Stack(
              children: [
                Positioned(
                  top: topLeft.dy,
                  child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 16),
                    width: MediaQuery.of(context).size.width - 32,
                    height: bottomRight.dy - topLeft.dy,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(15),
                      color: status == SoundsMessageStatus.canceling ? Colors.red : ColorUtil.primary,
                      boxShadow: [
                        BoxShadow(color: Colors.white, blurRadius: 20, offset: Offset(0,-50), spreadRadius: 50)
                      ],
                    ),
                    child: CustomPaint(
                      painter: WavePainterCopy(_soundsRecorder.amplitudeList),
                    ),
                  ),
                ),
                Positioned(
                  top: topLeft.dy - 30,
                  left: 0,
                  right: 0,
                  child: Center(
                    child: Text(
                    status == SoundsMessageStatus.canceling ? '松手取消' : '松手发送，上移取消',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.normal,
                      color: status == SoundsMessageStatus.canceling ? Colors.red : ColorUtil.color999999,
                      decoration: TextDecoration.none
                    ),
                  ),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
    Overlay.of(context).insert(_entry!);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onPanDown: (details) async {
        HapticFeedback.lightImpact();
        // 额外添加首次授权时，不能开启录音
        if (!await _soundsRecorder.hasPermission()) {
          return;
        }

        // 是否支持录音配置
        if (!await _soundsRecorder.isEncoderSupported()) {
          return;
        }

        // 显示语音输入UI
        _showRecordingMask();

        // 录制
        _soundsRecorder.beginRec(
          onStateChanged: (state) {
            debugPrint('________  onStateChanged: $state ');
          },
          onAmplitudeChanged: (amplitude) {
            debugPrint(
                '________  onAmplitudeChanged: ${amplitude.current} , ${amplitude.max} ');
          },
          onDurationChanged: (time) {
            debugPrint('________  onDurationChanged: $time ');
          },
          onCompleted: (path, time) {
            debugPrint('________  onCompleted: $path , $time ');

            if (time < 1) {
              _removeMask();
              SmartDialog.showToast('录制时间过短',displayType: SmartToastType.last);
              return;
            }

            // 录制状态松开/超过时长 直接发送语音内容
            if (_soundsRecorder.status.value == SoundsMessageStatus.recording) {
              widget.onSendSounds?.call(SendContentType.voice, path!);
              _removeMask();
            }
            // 取消发送
            else if (_soundsRecorder.status.value ==
                SoundsMessageStatus.canceling) {
              _removeMask();
            }
          },
        );
      },
      onPanUpdate: (details) {
        if ((details.globalPosition.dy) < widget.editAreaRenderBox!.localToGlobal(Offset.zero).dy) {
          if (_soundsRecorder.status.value != SoundsMessageStatus.canceling) {
            HapticFeedback.heavyImpact();
            _soundsRecorder.updateStatus(SoundsMessageStatus.canceling);
          }
        } else {
          if (_soundsRecorder.status.value != SoundsMessageStatus.recording) {
            HapticFeedback.heavyImpact();
            _soundsRecorder.updateStatus(SoundsMessageStatus.recording);
          }
        }
      },
      onPanEnd: (details) async {
        // 手势结束音频
        _soundsRecorder.endRec();
      },
      child: ValueListenableBuilder(
        valueListenable: _soundsRecorder.status,
        builder: (context, value, child) {
          if (widget.builder != null) {
            return widget.builder?.call(context, value);
          }

          return Container(
            width: double.infinity,
            alignment: Alignment.center,
            child: Text(
              value.title,
              style: const TextStyle(
                fontSize: 19,
                fontWeight: FontWeight.bold,
              ),
            ),
          );
        },
      ),
    );
  }
}